<template>
  <h2>会员</h2>
  <el-input
    v-model="searchQuery"
    placeholder="请输入搜索内容"
    style="margin-bottom: 20px; width: 300px;"
  />
  
  <router-link :to="{ name: 'AddUser' }">
      <el-button type="primary" style="margin-bottom: 20px;">
        添加用户
      </el-button>
    </router-link>

  <el-table :data="paginatedUsers" border="true" style="width: 100%">
    <el-table-column prop="name" label="会员姓名" width="180" />
    <el-table-column prop="sex" label="性别" width="180" />
    <el-table-column prop="MembershipCard" label="会员卡" width="180" />
    <el-table-column prop="MembershipDate" label="入会日期" width="180" />
    <el-table-column prop="note" label="备注" width="180" />
    <el-table-column label="操作" align="center">
      <template v-slot="scope">
        <el-button
          @click="editUser(scope.row)"
          type="primary"
          style="margin-right: 5px;"
        >
          <i class="el-icon-edit"></i> 编辑
        </el-button>
        <router-link :to="{ name: 'MembershipCardView', params: { name: scope.row.name } }">
          <el-button type="info" style="margin-right: 5px;">
            <i class="el-icon-view"></i> 查看
          </el-button>
        </router-link>
        <el-button @click="removeUser(scope.row)" type="danger">
          <i class="el-icon-delete"></i> 注销
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <div style="margin-top: 20px; text-align: center;">
    <span>
      当前第 {{ (currentPage - 1) * pageSize + 1 }} 条到第
      {{ Math.min(currentPage * pageSize, filteredTotalUsers) }} 条，共 {{ filteredTotalUsers }} 条
    </span>
  </div>

  <el-pagination
    style="margin-top: 20px;"
    background
    layout="total, prev, pager, next, jumper"
    :total="filteredTotalUsers"
    :page-size="pageSize"
    :current-page="currentPage"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />

  <el-dialog v-model="isEditDialogVisible" title="编辑用户">
      <el-form :model="editForm">
        <el-form-item label="会员姓名">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="editForm.sex">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期">
          <el-date-picker
            v-model="editForm.birthday"
            type="date"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="editForm.note"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">确定</el-button>
      </div>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getUsersList,submitEditForm,deleteMember } from '@/api/Membership';




const currentPage = ref(1);
const pageSize = ref(2);
const searchQuery = ref('');
const users = ref([]);
const isEditDialogVisible = ref(false);

const editForm = reactive({
  name: '',
  phone: '',
  sex: '',
  birthday: '',
  note: ''
});

const filteredUsers = computed(() => {
  if (!searchQuery.value) {
    return users.value;
  }
  return users.value.filter(user => 
    Object.values(user).some(value => 
      String(value).toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  );
});

const filteredTotalUsers = computed(() => filteredUsers.value.length);

const paginatedUsers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredUsers.value.slice(start, end);
});

const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

const fetchData = async () => {
      try {
          const res = await getUsersList();
          users.value=res.data;
          console.log(res);
      } catch (error) {
          console.error('Error:', error);
          alert('error');
      }
  };

onMounted(() => {
  fetchData();
});

const editUser = (row) => {
  Object.assign(editForm, row);
  isEditDialogVisible.value = true;
};

// const submitEdit = () => {
//   console.log("begin to submitEdit")
//   //
//   submitEditForm(editForm)
//   .then(res => {
//     console.log("==========>",res.data)

//   })
//   .catch(error => {
//     console.error('Error:', error);
//     alert('error');
//   })
// }

const submitEdit = () => {
  submitEditForm(editForm).then(res => {
    isEditDialogVisible.value = false;
    if (res.data.code === 200) {
      ElMessage({
      type: 'success',
      message: '用户信息已更新'
    });
    location.reload();
    }
  })
  .catch(error => {
    console.error('Error:', error);
    alert('error');
  })
};
const removeUser = (row) => {
  ElMessageBox.confirm(
    '此操作将永久注销该会员, 是否继续?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    deleteMember(row).then(res => {
      ElMessage({
        type: 'success',
        message: '会员已成功注销'
      });
      location.reload();
    })
    .catch(error => {
      console.error('Error:', error);
      alert('error');
    })
});
};


  
</script>

<style scoped>
</style>


